package com.xz.knowledgeDuplication.thread;

/**
 * @author 召
 * @date 2022-07-18 21:40:07
 */
public class Ticket implements Runnable{

    /**
     * 票数
     * volatile关键字保证程序有序性,可见性
     */
    private volatile int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <= 0) {
                break;
            }
            try {
                // 模拟延迟
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                if (ticketNums <= 0) {
                    break;
                }
                // Thread.currentThread().getName() 获取当前线程名称
                System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "票");
            }
        }
    }

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "小明").start();
        new Thread(ticket, "老师").start();
        new Thread(ticket, "黄牛").start();
    }
}
